package org.dei.perla.rockfall;

import java.io.BufferedReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;

import org.dei.dataserver.Server;
import org.dei.perla.parser.expressions.Constant;
import org.dei.perla.parser.expressions.ConstantID;
import org.dei.perla.parser.grammar.ParseException;
import org.dei.perla.parser.grammar.Parser;
import org.dei.perla.parser.statements.Query;
import org.dei.perla.parser.util.PairValue;
import org.dei.perla.rockfall.utils.DatabaseDump;
import org.dei.perla.sys.device.fpc.dspic.DSPicFPC;
import org.dei.perla.sys.llqruntime.QueryAnalyzer;

public class RockfallManager {
	
	private static final int MAX_FPC = 4;
	
	private ArrayList<DSPicFPC> dspicList;
	
	private static boolean firstRun = true;
	
	public RockfallManager() {
		
		dspicList = new ArrayList<DSPicFPC>();
		
		// Inizializzo il server
		Server s = new Server(5606);
		s.start();
		
		// Istanzio ed aggancio le fpc al server ed al database dumper
		for (int i = 0; i < MAX_FPC; i++){
			DSPicFPC tTempFpc = new DSPicFPC(s.getFpcPipes(i), i);
			dspicList.add(tTempFpc);
			Thread dbDump = new Thread(new DatabaseDump(tTempFpc.registerQuery(null)));
			dbDump.start();
		}
	}
	
	public Iterator<DSPicFPC> getDSPicIterator() {
		return dspicList.iterator();
	}
	
	public void executeQuery(String query) {
		
		StringReader reader = new StringReader(query);
		
		ArrayList<PairValue<String, ? extends Constant>> pAttributeToSetList = new ArrayList<PairValue<String, ? extends Constant>>();
		
		if (firstRun) {
			new Parser(new BufferedReader(reader));
			firstRun = false;
			
		} else {
			Parser.ReInit(new BufferedReader(reader));
		}
		
		try {
			Query parsedQuery = Parser.StatementSequence();
			QueryAnalyzer queryAnalizer = new QueryAnalyzer(parsedQuery);
			
			for (String tAttributeToSet : queryAnalizer.getAttributeToSet().keySet()){
				pAttributeToSetList.add(new PairValue<String, Constant>(tAttributeToSet, queryAnalizer.getAttributeToSet().get(tAttributeToSet)));
			}
			
			for (ConstantID id : queryAnalizer.getDeviceToSetID()) {
				dspicList.get(id.getValueInt()).setUpdateAttributes(pAttributeToSetList);
			}
			
		} catch (ParseException e) {
			e.printStackTrace();
		} 
	}
}
